package it.traveldream.entities;

import it.traveldream.dto.ReservationDTO;
import it.traveldream.dto.UserDTO;
import it.traveldream.utils.DigestUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.CascadeType;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.OneToMany;

/**
 * Entity implementation class for Entity: Customer
 *
 */
@Entity
@DiscriminatorValue("Customer")
public class Customer extends User {

	public static final int BASIC_DISCOUNT_VALUE = 50;
	private static final long serialVersionUID = 1L;
	public static final String role = "CUSTOMER";
	
	@OneToMany(mappedBy = "customer", cascade = CascadeType.ALL)
	private List<CustomerInvites> friendsInvited; 
	
	@OneToMany(mappedBy = "customer", cascade = CascadeType.ALL)
	private List<Reservation> reservations;
	
	private int discountPercentage;

	public Customer() {
		super();
	}

	public Customer(UserDTO user) {
		this.setMail(user.getEmail());
		try {
			this.setPwdHash(DigestUtils.sha512Hex(user.getPassword()));
		} catch (Exception e) {
			throw new IllegalArgumentException("Error in hashing password. Not supported algorithm?");
		}
		
		if (user.getUsername().equals(""))
			this.setUserName(user.getEmail());
		else this.setUserName(user.getUsername());
	}

	public List<CustomerInvites> getFriendsInvited() {
		return this.friendsInvited;
	}

	public void setFriendsInvited(List<CustomerInvites> friendsInvited) {
		this.friendsInvited = friendsInvited;
	}

	public int getDiscountPercentage() {
		return this.discountPercentage;
	}

	public void setDiscountPercentage(int discountPercentage) {
		this.discountPercentage = discountPercentage;
	}

	public List<Reservation> getReservations() {
		return this.reservations;
	}

	public UserDTO toDTO() {
		UserDTO dto = new UserDTO();
		
		dto.setEmail(this.getMail());
		dto.setUsername(this.getUserName());
		dto.setDiscountPercentage(this.discountPercentage);
		
		List<ReservationDTO> reservations = new ArrayList<>();
		for (Reservation r : this.reservations)
			reservations.add(r.toDTO(dto));
		dto.setReservations(reservations);
		
		Map<ReservationDTO, String> invites = new HashMap<>();
		for (CustomerInvites i : this.friendsInvited){
			invites.put(i.getReservation().toDTO(dto), i.getFriendAddress());
		}
		dto.setFriendsInvited(invites);
		return dto;
	}
   
}
